<template>
  <div style="font-size: 18rem; box-sizing: border-box">
    <header>
      <div class="icon" @click="$router.back()"><van-icon name="cross" /></div>
      <div style="font-size: 16rem">帮助</div>
    </header>
    <main>
      <h1>欢迎来到猫眼</h1>
      <div class="phone">
        <input type="text" v-model="phone" placeholder="请输入手机号码" />
      </div>
      <div class="password_input" v-if="ispass" >
        <van-field v-model="password" type="password" placeholder="请输入密码" />
      </div>
      <p class="tip">未注册的手机号验证后自动创建猫眼账户</p>
      <div class="word">
        <span class="chekbox"
          ><van-checkbox checked-color="red" icon-size="16rem" v-model="checked"></van-checkbox
        ></span>
        <span>
          <van-highlight :keywords="keywords" :source-string="text" />
        </span>
      </div>
      <!-- <van-cell title="展示弹出层" is-link @click="a" /> -->
      <template v-if="ispass === false">
        <div class="getmess" @click="getmess">
          {{ code ? '继续输入验证码' : '获取短信验证码' }}
        </div>
        <van-popup :show="show" position="bottom" :style="{ height: '100%' }">
          <div class="up_main">
            <div class="up-icon" @click="closeup">
              <span><van-icon name="cross" color="#999" /></span>
            </div>
            <div class="up-text">
              <h2>请输入你收到的验证码</h2>
            </div>
            <div class="up-num">
              <van-password-input
                :value="numvalue"
                :mask="false"
                :focused="showKeyboard"
                @focus="showKeyboard = true"
              />
              <!-- 数字键盘 -->
              <van-number-keyboard
                v-model="numvalue"
                :show="showKeyboard"
                @blur="showKeyboard = false"
              />
            </div>
          </div>
        </van-popup>
      </template>
      <template v-else>
        <div class="getmess" @click="login">登录</div>
      </template>

      <div class="toggle">
        <span @click="passwordTime"> {{ ispass ? '验证码登录' : '密码登录' }} </span
        ><span>遇到问题</span>
      </div>
      <div v-if="code">验证码：{{ code }}</div>
    </main>
  </div>
</template>
    
<script setup lang='ts'>
import { ref, watch } from 'vue'
import { showNotify, showFailToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute() // 用于获取当前路由对象
const router = useRouter() // 用于执行路由跳转

// 引入pinia内方法 -lxz

import { FilmDataObj } from '../../stores/LXZ'
// 获取pinia实例内容
const Ordersdata = FilmDataObj()

const { updateOrdersArray } = Ordersdata

const $router = useRouter()
const checked = ref(false)
const text =
  '我已阅读并同意《猫眼用户服务协议》和《隐私政策》并授权猫眼使用该猫眼账号信息（如昵称，头像，收获地址）以便统一管理'
const keywords = ['《猫眼用户服务协议》', '《隐私政策》']
const phone = ref('')
const code = ref('')
const show = ref(false)
const ispass = ref(false)
const password = ref('')
// 手机号码正则（中国大陆手机号）
const phoneRegex = /^1[3-9]\d{9}$/

// 密码登录
const passwordTime = () => {
  ispass.value = !ispass.value
}
const closeup = () => {
  show.value = false
  numvalue.value = ''
}
// 设置令牌
const setToken = (usertoken) => {
  const token = usertoken

  localStorage.setItem('token', JSON.stringify(usertoken))
  localStorage.setItem('token2', JSON.stringify(phone.value))
}
// 获取验证码以及判断登录
const getmess = () => {
  if (!checked.value) {
    showFailToast('请先同意协议')
    return
  }

  // 校验手机号码格式
  if (!phoneRegex.test(phone.value)) {
    showFailToast('请输入正确的手机号码')
    return
  }

  if (code.value === '') {
    const characters = '0123456789'
    code.value = Array.from({ length: 6 }, () =>
      characters.charAt(Math.floor(Math.random() * characters.length))
    ).join('')
    showNotify({
      type: 'primary',
      message: `短信验证码已发送,验证码为：${code.value}`,
      duration: 5000,
      zIndex: 10001,
    })
    show.value = true
  } else {
    show.value = true
  }
}
// 登录功能
const login = () => {
  // 校验协议是否勾选
  if (!checked.value) {
    showFailToast('请先同意协议')
    return
  }

  // 校验手机号码格式
  if (!phoneRegex.test(phone.value)) {
    showFailToast('请输入正确的手机号码')
    return
  }

  // 校验密码
  if (password.value.length < 6) {
    showFailToast('密码长度不能小于6位')
    return
  }

  // 从 localStorage 获取现有用户数据
  const existingUsers = JSON.parse(localStorage.getItem('users')) || []

  // 检查是否存在该手机号
  const existingUser = existingUsers.find((user) => user.tel === phone.value)

  if (existingUser) {
    // 用户已存在，验证密码是否正确（这里假设密码为固定值123456）
    if (password.value === '123456') {
      setToken(existingUser.username) // 设置登录状态
      showFailToast('登录成功')
      // 更新订单列表数据 -lxz
      updateOrdersArray()

      // 跳转到目标页面
      const target = route.query.target || '/'
      router.replace(target).catch((err) => {
        if (err.name !== 'NavigationDuplicated') {
          console.error('导航错误：', err)
        }
      })
    } else {
      showFailToast('密码错误')
    }
  } else {
    // 用户不存在，进行注册
    const randomNum = Math.floor(1000 + Math.random() * 9000) // 生成随机用户名
    const newUser = {
      username: `用户${randomNum}`,
      gender: '男',
      tel: phone.value,
    }

    // 保存新用户到 localStorage
    existingUsers.push(newUser)
    localStorage.setItem('users', JSON.stringify(existingUsers))

    // 设置 Token 并跳转
    setToken(newUser.username)
    showFailToast('注册并登录成功')
    // 更新订单列表数据 -lxz
    updateOrdersArray()

    // 跳转到目标页面
    const target = route.query.target || '/'
    router.replace(target).catch((err) => {
      if (err.name !== 'NavigationDuplicated') {
        console.error('导航错误：', err)
      }
    })
  }
}
const showKeyboard = ref(true)
const numvalue = ref('')
// 监听 numvalue 的变化
watch(numvalue, (Vm) => {
  if (Vm.length === 6) {
    if (Vm === code.value) {
      // 验证码正确，处理登录或注册逻辑
      const randomNum = Math.floor(1000 + Math.random() * 9000) // 随机数生成
      const existingUsers = JSON.parse(localStorage.getItem('users')) || [] // 获取用户列表

      // 检查用户是否已存在
      const existingUser = existingUsers.find((user) => user.tel === phone.value)

      if (existingUser) {
        // 用户已存在，直接登录
        setToken(existingUser.username) // 设置登录状态
        showFailToast('登录成功')
        // 更新订单列表数据 -lxz
        updateOrdersArray()
      } else {
        // 用户不存在，进行注册
        const newUser = {
          username: `用户${randomNum}`,
          gender: '男',
          tel: phone.value,
          wantwatch: [],
        }

        // 添加新用户到列表并保存
        existingUsers.push(newUser)
        localStorage.setItem('users', JSON.stringify(existingUsers))

        // 设置登录状态
        setToken(newUser.username)
        showFailToast('注册并登录成功')
        // 更新订单列表数据 -lxz
        updateOrdersArray()
      }

      // 跳转到目标页面
      const target = route.query.target || '/'
      router.replace(target).catch((err) => {
        if (err.name !== 'NavigationDuplicated') {
          console.error('导航错误：', err)
        }
      })
    } else {
      // 验证码错误
      showFailToast('验证码错误')
    }
  }
})
</script>
    
<style lang="less" scoped>
header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rem;
  .icon {
    padding: 10rem;
    background-color: #cccccc30;
    border-radius: 50%;
  }
}
main {
  padding: 20rem;
  h1 {
    font-weight: 400;
    margin-bottom: 60rem;
  }
  .phone {
    input {
      box-sizing: border-box;
      width: 100%;
      border: none;
      padding: 5rem;
      border-bottom: 1rem solid rgba(0, 0, 0, 0.289);
    }
  }
  .password_input {
    margin-top: 20rem;
    border-bottom: 1rem solid rgba(0, 0, 0, 0.289);
    :deep(.van-cell) {
      padding: 5rem;
      font-size: 18rem;
    }
  }
  .tip {
    margin-top: 10rem;
    font-size: 14rem;
    color: #888;
    margin-bottom: 80rem;
  }
  .word {
    margin-top: 20rem;
    display: flex;
    font-size: 14rem;
    color: #888;
    .chekbox {
      margin-right: 10rem;
    }
  }
  .getmess {
    background-color: #f50027;
    font-weight: 600;
    color: white;
    text-align: center;
    border-radius: 20rem;
    margin-top: 30rem;
    padding: 10rem 0;
  }
  .toggle {
    display: flex;
    justify-content: space-between;
    margin-top: 30rem;
    font-size: 14rem;
    color: #999;
  }
  .up_main {
    .up-icon {
      padding: 40rem 20rem;
      > span {
        padding: 10rem;
        background-color: #8888884e;
        border-radius: 50%;
      }
    }
    .up-text {
      margin-top: 80rem;
      text-align: center;
    }
    .up-num {
      margin-top: 80rem;
    }
  }
}
</style>